<?
define ( 'TIPH_ROOT', dirname ( __FILE__ ) . '/../tiph' );
define ( 'DIR_ROOT', dirname ( __FILE__ ) );
define ( 'UPLOAD_ROOT', dirname(__FILE__) . '/webroot/upload');
require_once (TIPH_ROOT . '/web/application.php');
require_once (dirname ( __FILE__ ) . '/config.php');

class NeedLoginException extends Exception {
}

class NotFoundException extends Exception {
}

class LoginedController extends Controller {
	public function init() {
		Model::load('LoginModel');
		if(!LoginModel::getUname()) {
			throw new NeedLoginException();
		}
	}
}

class App extends Application {
	
	public function handleException($e) {
		if ($e instanceof NeedLoginException) {
			G ('');
			return;
		}
		if ($e instanceof NotFoundException) {
			echo "404 page not found. sorry.";
			return;
		}
		if ($e instanceof TiphException) {
			switch ($e->type) {
				case EX_BAD_ROUTER :
					echo "404 page not found. sorry.";
					break;
				default :
					echo "500 internal error.";
					break;
			}
			return;
		}
		echo "500 internal error.";
	}
	
	public function shutdown() {
		Cache::close ();
		DB::close ();
	}
	
	public function init() {
		global $_APP;
		
		date_default_timezone_set ( 'Asia/Shanghai' );
		
		/* TIPH Config */
		require_once (TIPH_ROOT . '/base/db.php');
		DB::register ( $_APP ['config'] ['db'] );
		
		require_once (TIPH_ROOT . '/base/session.php');
		require_once (TIPH_ROOT . '/base/cookie.php');
		Cookie::register ( $_APP ['config'] ['cookie'] );
		
		require_once (TIPH_ROOT . '/base/cache.php');
		Cache::register ( $_APP ['config'] ['cache'] );
		
		require_once (TIPH_ROOT . '/web/view.php');
		View::register ( array (
			'view_root' => dirname ( __FILE__ ) . '/view' ) );
		
		require_once (TIPH_ROOT . '/base/model.php');
		Model::register ( array (
			'root' => dirname ( __FILE__ ) . '/model' ) );
		
		require_once (TIPH_ROOT . '/web/dispatcher.php');
		$dispatcher = $this->_dispatcher;
		$router_map = array (
			'job' => 'JobController',
			'login' => 'LoginController',
			'' => 'HomeController' );
		$dispatcher->register ( array (
			'context_root' => '/hcs/', 
			'controller_root' => dirname ( __FILE__ ) . '/controller', 
			'router_map' => $router_map ) );
	
	}
}
